package com.atguigu.tingshu.order.receiver;

import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.order.service.OrderInfoService;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RedissonClient;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * ClassName: OrderReceiver
 * Package: com.atguigu.tingshu.receiver
 * Description:
 *
 * @Author:
 * @Create: 2025/8/6 - 22:12
 * @Version: v1.0
 */
@Component
@Slf4j
public class OrderReceiver {

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private OrderInfoService orderInfoService;

    @PostConstruct
    public void listener() {
        new Thread(() -> {
            while (true) {
                RBlockingDeque<String> blockingDeque = this.redissonClient
                        .getBlockingDeque(KafkaConstant.QUEUE_ORDER_CANCEL);
                try {
                    String orderId = blockingDeque.take();
                    if(StringUtils.hasText(orderId)){
                        this.orderInfoService.orderCancel(Long.valueOf(orderId));
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }

    @KafkaListener(topics = KafkaConstant.QUEUE_ORDER_PAY_SUCCESS)
    public void orderPaySuccess(ConsumerRecord<String, String> record) {
        //  获取数据
        String orderNo = record.value();
        if (!StringUtils.isEmpty(orderNo)){
            // 修改订单状态
            orderInfoService.orderPaySuccess(orderNo);
        }
    }
}
